package com.hpin.mlxteacher.fragment;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.BabyTreeAdapter;
import com.hpin.mlxteacher.adapter.SchoolClassAdapter;
import com.hpin.mlxteacher.base.BaseFragment;
import com.hpin.mlxteacher.bean.BabayTreeData;
import com.hpin.mlxteacher.bean.BabyTreeRes;
import com.hpin.mlxteacher.bean.SchoolClassReq;
import com.hpin.mlxteacher.pulltorefush.PullToRefreshBase;
import com.hpin.mlxteacher.pulltorefush.PullToRefreshListView;
import com.hpin.mlxteacher.tree.ReleaseActivity;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.DensityUtil;
import com.hpin.mlxteacher.utils.HttpUtil;

import java.util.ArrayList;
import java.util.List;

//import com.umeng.analytics.MobclickAgent;

/**
 * 宝宝树fragment
 * Created by Administrator on 2015/7/15.
 */
public class BabyTreeFragment extends BaseFragment implements View.OnClickListener {

    private int currentPageNum;

    private List<BabayTreeData> babayTreeDatas = new ArrayList<BabayTreeData>();
    private PullToRefreshListView plv_friend;
    private BabyTreeAdapter babyTreeAdapter;
    private SchoolClassAdapter schoolClassAdapter;
    //    private String currentClassId;
    private SchoolClassReq classReq;
    private ListView listView;
    //    private EditText et_comment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View babyTreeView = inflater.inflate(R.layout.fragment_baby_tree, null);

        initWidget(babyTreeView);

        babyTreeAdapter.setFragmentView(babyTreeView);

        return babyTreeView;
    }

    @Override
    public void onResume() {
        super.onResume();

//        MobclickAgent.onPageStart(getClass().getName()); //统计页面

        currentPageNum = 0;

        //如果没有选择班级 则获取班级信息
        if (CommonUtils.isNull(sp.getString(Constant.classId, ""))) {
            myClasses(null);
        } else {
            //选择了班级
            tv_title.setText(sp.getString(Constant.className, ""));
            getBabyTreeData();
        }

    }

    public void onPause() {
        super.onPause();

        //清空集合,防止新发布的 宝宝树 被添加到最下面
        if (babayTreeDatas != null) {
            babayTreeDatas.clear();
        }

//        MobclickAgent.onPageEnd(getClass().getName());
    }

    private TextView tv_title;
    private TextView tv_right;

    private void initWidget(View babyTreeView) {

//        TextView tv_left = (TextView) babyTreeView.findViewById(R.id.tv_left);
        tv_title = (TextView) babyTreeView.findViewById(R.id.tv_title);
        tv_right = (TextView) babyTreeView.findViewById(R.id.tv_right);
        tv_right.setVisibility(View.VISIBLE);

//        RelativeLayout rl_page = (RelativeLayout) babyTreeView.findViewById(R.id.rl_page);
//
//        rl_page.setOnClickListener(this);
        tv_title.setOnClickListener(this);

//        tv_left.setText(getResources().getString(R.string.rl_baby_tree));
        tv_title.setText(getResources().getString(R.string.rl_baby_tree));
        tv_right.setText(getResources().getString(R.string.baby_tree_release));

//        et_comment = (EditText) babyTreeView.findViewById(R.id.et_comment);

        plv_friend = (PullToRefreshListView) babyTreeView.findViewById(R.id.plv_friend);

        listView = plv_friend.getRefreshableView();

        babyTreeAdapter = new BabyTreeAdapter(getActivity(), babayTreeDatas);
        plv_friend.setAdapter(babyTreeAdapter);

        RelativeLayout title = (RelativeLayout) babyTreeView.findViewById(R.id.title);
        title.setOnClickListener(this);

        //设置上啦和下拉都可以
        plv_friend.setMode(PullToRefreshBase.Mode.BOTH);

        plv_friend.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(),
                        DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);

                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                //下拉刷新
                currentPageNum = 0;

                if (babayTreeDatas != null)
                    babayTreeDatas.clear();

                getBabyTreeData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME
                        | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                //上啦加载更多
                ++currentPageNum;
                getBabyTreeData();
            }
        });

        tv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(getActivity(), ReleaseActivity.class);
                startActivity(intent);
            }
        });

    }

    /**
     * 获取宝宝树数据
     */
    private void getBabyTreeData() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("pageNum", currentPageNum);
        j.put("classId", sp.getString(Constant.classId, ""));

        HttpUtil.setPostRequest("获取信息中...", getActivity(), Constant.WEB_ROOT + Constant.GETTREE,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        plv_friend.onRefreshComplete();

                        try {

                            BabyTreeRes babyTreeRes = JSONObject.parseObject(str, BabyTreeRes.class);

                            if (babyTreeRes.code == Constant.SUCCESS) {

                                if (babyTreeRes.data != null) {

//                                    //防止切换到另外一个班级的时候 当前班级没有宝宝树
//                                    if (babyTreeRes.data.size()<1 && currentPageNum == 0) {
//                                        babyTreeAdapter.setBabayTreeDatas(babyTreeRes.data);
//                                        babyTreeAdapter.notifyDataSetChanged();
//                                        return;
//                                    }

                                    if (babyTreeRes.data.size() == 0) {
                                        babayTreeDatas = babyTreeRes.data;

                                        if (currentPageNum > 0) {
                                            showToast("当前已经是最后一页");
                                            return;
                                        }

                                    }

                                    setDataView(babyTreeRes.data);
                                    babyTreeAdapter.setBabayTreeDatas(babayTreeDatas);
                                    babyTreeAdapter.notifyDataSetChanged();
                                }

                            } else {
                                showToast(Constant.showErrorMsg(babyTreeRes.code, getActivity()));
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
//                            LogUtil.e("TAG", "===宝宝树解析错误===");
                        }

                    }
                }, new HttpUtil.FailListener() {
                    @Override
                    public void setOnFailListener() {

                        plv_friend.onRefreshComplete();
                        if (currentPageNum == 0) {

                            if (babayTreeDatas != null && babyTreeAdapter != null) {
                                babayTreeDatas.clear();
                                babyTreeAdapter.setBabayTreeDatas(babayTreeDatas);
                                babyTreeAdapter.notifyDataSetChanged();
                            }

                        }
                    }
                });

    }

    /**
     * 获取我的班级
     */
    private void myClasses(final View v) {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));

        HttpUtil.setPostRequest("获取班级中...", getActivity(), Constant.WEB_ROOT + Constant.MYCLASSES,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            classReq = JSONObject.parseObject(str, SchoolClassReq.class);

                            if (classReq.code == Constant.SUCCESS) {

                                if (classReq.data != null && classReq.data.size() > 0) {

                                    if (v != null) {
                                        showPup(classReq, v);
                                    } else {    //第一次进入 默认选择第一个
                                        SharedPreferences.Editor edit = sp.edit();
                                        edit.putString(Constant.classId, classReq.data.get(0).id);
                                        edit.putString(Constant.className, classReq.data.get(0).nickName);
                                        edit.apply();

                                        tv_title.setText(sp.getString(Constant.className, ""));
                                        getBabyTreeData();
                                    }
                                }

                            } else
                                showToast(Constant.showErrorMsg(classReq.code, getActivity()));

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    /**
     * 如果有更多则进行重复判断
     *
     * @param temp 新的集合
     */
    protected void setDataView(List<BabayTreeData> temp) {

        if (babayTreeDatas.size() == 0) {
            babayTreeDatas = temp;
            return;
        }

        int nowSize = babayTreeDatas.size();
        int newSize = temp.size();
        for (int i = 0; i < newSize; i++) {
            boolean exist = true;
            BabayTreeData mcod = temp.get(i);
            for (int j = 0; j < nowSize; j++) {
                BabayTreeData nmcod = babayTreeDatas.get(j);
                if (mcod.tree.id.equals(nmcod.tree.id)) {
                    exist = false;
                    break;
                }
            }

            if (exist)
                babayTreeDatas.add(mcod);
        }
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {

            case R.id.tv_title:  //选择班级

                if (classReq != null) {

                    showPup(classReq, view);//已经加载过班级信息 直接弹出提示
                } else {

                    myClasses(view);//未加载过班级信息, 先获取班级信息
                }
                break;

            case R.id.title: // 回到顶部

//                LogUtil.e("tag", "回到顶部");

//                listView.sets

                if (!listView.isStackFromBottom()) {
//                    listView.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
                    listView.setStackFromBottom(true);
                }
                listView.setStackFromBottom(false);

                break;

//            case R.id.rl_page:
//
//                InputMethodManager imm = (InputMethodManager)
//                        getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
//                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
//                break;

        }

    }

    /**
     * 弹出选择popu的窗口
     *
     * @param classReq
     * @param v
     */
    private void showPup(final SchoolClassReq classReq, View v) {

        //先把图标改为箭头向上的
        tv_title.setBackgroundResource(R.drawable.choose_class_up);

        View popuView = View.inflate(getActivity(), R.layout.layout_choose_class, null);

        final PopupWindow classDialog = new PopupWindow(popuView,
                DensityUtil.dip2px(getActivity(), 100), ViewGroup.LayoutParams.WRAP_CONTENT);
        classDialog.setOutsideTouchable(true);
        classDialog.setFocusable(true);
        classDialog.setBackgroundDrawable(new BitmapDrawable());
        //x y   DensityUtil.dip2px(getActivity(), 5)
//        classDialog.showAsDropDown(v, 0, DensityUtil.dip2px(getActivity(), 5)); //0 0  x y 轴的偏移量
        classDialog.showAsDropDown(v, 0, 0); //0 0  x y 轴的偏移量
        //屏幕变暗
        changeScreen(0.5f);

        ListView lv_class = (ListView) popuView.findViewById(R.id.lv_class);

//        temList = classReq.data;
        schoolClassAdapter = new SchoolClassAdapter(getActivity(), classReq.data);

        lv_class.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //选择班级
                if (classReq != null && classReq.data != null && classReq.data.size() > 0) {

                    if (sp.getString(Constant.classId, "").equals(classReq.data.get(i).id)) {
                        if (classDialog != null && classDialog.isShowing())
                            classDialog.dismiss();
                        return;//跟上次选择的是同一个班级, 不需要更新页面
                    }

                    //保存选择中班级id和班级名称
                    SharedPreferences.Editor edit = sp.edit();
                    edit.putString(Constant.classId, classReq.data.get(i).id);
                    edit.putString(Constant.className, classReq.data.get(i).nickName);
                    edit.apply();
                    tv_title.setText(classReq.data.get(i).nickName);

                    //清空集合,防止数据混乱
                    if (babayTreeDatas != null)
                        babayTreeDatas.clear();

                    currentPageNum = 0;
                    getBabyTreeData();
                }

                if (classDialog != null && classDialog.isShowing())
                    classDialog.dismiss();

            }
        });

        lv_class.setAdapter(schoolClassAdapter);

        classDialog.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                changeScreen(1f);
                //把图标改为箭头向下的
                tv_title.setBackgroundResource(R.drawable.choose_class_down);
            }
        });
    }

    private void changeScreen(float f) {

        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = f;
        lp.dimAmount = f;
        getActivity().getWindow().setAttributes(lp);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

//        mApplication.cancelPendingRequests(getClass().getName());

    }
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent ev) {
//        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
//            View v = getActivity().getCurrentFocus();
//            if (isShouldHideInput(v, ev)) {
//
//                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
//                if (imm != null) {
//                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
//                }
//            }
//            return super.dispatchTouchEvent(ev);
//        }
//        // 必不可少，否则所有的组件都不会有TouchEvent了
//        if (getWindow().superDispatchTouchEvent(ev)) {
//            return true;
//        }
//        return onTouchEvent(ev);
//    }


//    private  boolean isShouldHideInput(View v, MotionEvent event) {
//        if (v != null && (v instanceof EditText)) {
//            int[] leftTop = { 0, 0 };
//            //获取输入框当前的location位置
//            v.getLocationInWindow(leftTop);
//            int left = leftTop[0];
//            int top = leftTop[1];
//            int bottom = top + v.getHeight();
//            int right = left + v.getWidth();
//            if (event.getX() > left && event.getX() < right
//                    && event.getY() > top && event.getY() < bottom) {
//                // 点击的是输入框区域，保留点击EditText的事件
//                return false;
//            } else {
//                return true;
//            }
//        }
//        return false;
//    }

}